package com.gzedu.module.controller.user;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gzedu.module.faced.user.UserFaced;
import com.gzedu.module.modle.user.User;

import net.sf.json.JSONArray;

@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserFaced userFacade;
	
	
	
	@RequestMapping("/showUser")  
    public String toIndex(HttpServletRequest request,Model model){
        String userName;
		try {
			userName = new String(ObjectUtils.toString(request.getParameter("userName")).getBytes("ISO-8859-1"),"UTF-8");
			User user = this.userFacade.getUserByName(userName);
	        model.addAttribute("user", user);  
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
        
        return "showUser";  
    }
	
	/**
	 * 用户新增页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/add")
	public String add(HttpServletRequest request, HttpServletResponse response){
		return "/views/user/userForm";
	}
	
	/**
	 * 用户新增
	 * @param request
	 * @param response
	 * @param user
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public Map<String,Object> save(HttpServletRequest request,HttpServletResponse response,User user){
		Map<String,Object> map = new HashMap<String,Object>();
		boolean flag = userFacade.save(user);
		map.put("flag", flag);
		return map;
	}
	
	/**
	 * 用户修改
	 * @param request
	 * @param response
	 * @param model
	 * @param user
	 * @return
	 */
	@RequestMapping("/update")
	public String update(HttpServletRequest request,HttpServletResponse response, Model model,User user){
		User userInfo = userFacade.getUser(user);
		if(userInfo != null){
			model.addAttribute("id", userInfo.getId());
			model.addAttribute("userName", userInfo.getUserName());
			model.addAttribute("password", userInfo.getPassword());
			model.addAttribute("age", userInfo.getAge());
		}
		return "/views/user/userForm";
	}
}
